package cn.com.cifi.mars.service.impl;

import cn.com.cifi.mars.constant.IsDeleteEnum;
import cn.com.cifi.mars.entity.PriceValueOrg;
import cn.com.cifi.mars.entity.PriceValueOrgBackups;
import cn.com.cifi.mars.entity.PriceVersion;
import cn.com.cifi.mars.mapper.mars.PriceValueOrgMapper;
import cn.com.cifi.mars.service.PriceValueOrgBackupsService;
import cn.com.cifi.mars.util.UUIDUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.entity.PriceVersionBackups;
import cn.com.cifi.mars.mapper.mars.PriceVersionBackupsMapper;
import cn.com.cifi.mars.service.PriceVersionBackupsService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 价格版本备份表 服务实现类
 * </p>
 *
 * @author plx
 * @since 2020-05-20
 */
@Service
public class PriceVersionBackupsServiceImpl extends ServiceImpl<PriceVersionBackupsMapper, PriceVersionBackups> implements PriceVersionBackupsService {

    @Autowired
    private PriceVersionBackupsService priceVersionBackupsService;

    @Autowired
    private PriceValueOrgBackupsService priceValueOrgBackupsService;

    @Autowired
    private PriceValueOrgMapper priceValueOrgMapper;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void refreshSaveInfo(PriceVersion oldPriceVersion, PriceVersionBackups priceVersionBackups, LocalDateTime now) {

        List<PriceValueOrgBackups> orgBackups = new ArrayList<PriceValueOrgBackups>();
        QueryWrapper<PriceValueOrg> orgWrapper = new QueryWrapper<PriceValueOrg>();
        orgWrapper.eq("version_id", oldPriceVersion.getId())
                .eq("is_delete", IsDeleteEnum.NO.getKey());
        List<PriceValueOrg> orgList = priceValueOrgMapper.selectList(orgWrapper);
        if (CollectionUtils.isNotEmpty(orgList)){
            for (PriceValueOrg org : orgList){
                PriceValueOrgBackups newOrg = new PriceValueOrgBackups();
                BeanUtils.copyProperties(org, newOrg);
                newOrg.setId(UUIDUtils.create());
                newOrg.setBackupsId(org.getId());
                newOrg.setBackupsVersionId(priceVersionBackups.getId());
                newOrg.setUpdateTime(now);
                orgBackups.add(newOrg);
            }
        }
        //保存备份信息
        priceVersionBackupsService.save(priceVersionBackups);
        priceValueOrgBackupsService.saveBatch(orgBackups);
    }
}
